import commonEvent from '@ohos.commonEvent'

const TAG: string = 'BT_Demo[ScreenLockEventListener]'

export default class ScreenLockEventListener {
    private subscriber = null; // Used to save the created subscriber object for subsequent subscription and unsubscription.
    private callBack: (state: boolean)=> void = null

    // Subscriber information.
    private subscribeInfo = {
        events: ["usual.event.SCREEN_OFF", "usual.event.SCREEN_ON"]
    };

    // Callback for common event subscription.
    private SubscribeCallBack(err, data) {
        if (err.code) {
            console.error(`${TAG} SubscribeCallBack subscribe failed ` + JSON.stringify(err));
        } else {
            let screenUnLocked: boolean = data.event !== "usual.event.SCREEN_OFF"
            if (this.callBack != null) {
                this.callBack(screenUnLocked)
            }
        }
    }

    // Callback for subscriber creation.
    private CreateSubscriberCallBack(err, commonEventSubscriber) {
        if (err.code) {
            console.error(`${TAG} createSubscriber failed ` + JSON.stringify(err));
        } else {
            console.info(`${TAG} created Subscriber`);
            this.subscriber = commonEventSubscriber;
            // Subscribe to a common event.
            commonEvent.subscribe(this.subscriber, this.SubscribeCallBack.bind(this));
        }
    }

    // Callback for common event unsubscription.
    private UnsubscribeCallBack(err) {
        if (err.code) {
            console.info(`${TAG} unsubscribe failed ` + JSON.stringify(err));
        } else {
            console.info(`${TAG} unsubscribed`);
            this.subscriber = null
        }
    }

    public subscribe(on: boolean, callBack: (state: boolean)=> void = null) {
        this.callBack = callBack
        if (on) {
            if (this.subscriber != null) {
                console.info(`${TAG} subscriber already used`);
                return
            }
            // Create a subscriber.
            commonEvent.createSubscriber(this.subscribeInfo, this.CreateSubscriberCallBack.bind(this));
        }
        else {
            if (this.subscriber == null) {
                console.info(`${TAG} subscriber is clean`);
                return
            }
            // Unsubscribe from the common event.
            commonEvent.unsubscribe(this.subscriber, this.UnsubscribeCallBack.bind(this));
        }
    }
}